package agent

import (
	"context"
	"errors"
	"sort"

	"gitee.com/liuxuezhan/ar-platform/admin-api/internal/svc"
	"gitee.com/liuxuezhan/ar-platform/admin-api/internal/types"
	"gitee.com/liuxuezhan/ar-platform/rpc-client/agentClient/rpc"
	gameManagePb "gitee.com/liuxuezhan/ar-platform/rpc-client/gameManageClient/pb"
	"github.com/zeromicro/go-zero/core/logc"
	"github.com/zeromicro/go-zero/core/logx"
)

type GetRebatesFeeRateListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewGetRebatesFeeRateListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetRebatesFeeRateListLogic {
	return &GetRebatesFeeRateListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *GetRebatesFeeRateListLogic) GetRebatesFeeRateList(req *types.RebatesFeeRateListReq) (resp *types.RebatesFeeRateList, err error) {
	// 返佣费率管理--列表
	rpcReq := &rpc.RebatesFeeRateManagerListReq{
		Level: req.Level,
	}

	rpcResp, err := l.svcCtx.AgentRPC.GetRebatesFeeRateList(context.Background(), rpcReq)
	if err != nil {
		logc.Error(l.ctx, err)
		return nil, errors.New("failed to get rebates fee rate list")
	}

	// 游戏列表: 由配置改为从grpc游戏接口获取,数据结构保持不变,保持前后端一致
	gameCategoryList, err := l.svcCtx.GameManageRpc.GameCategoryList(l.ctx, &gameManagePb.GameCategoryListReq{
		IsEnabled: 1,
	})
	if err != nil {
		return nil, errors.New("failed to get game category list")
	}

	// 解析detail数据
	_typeSlice := make([]string, 0)
	_nameSlice := make([]string, 0)
	for _, v := range gameCategoryList.List {
		_typeSlice = append(_typeSlice, v.Code)
		_nameSlice = append(_nameSlice, v.Name+"(%)")
	}

	_data := make([]types.RebatesFeeRateInfo, len(rpcResp.Data))

	for i, _row := range rpcResp.Data {
		_list := make([]types.RebatesFeeRateForList, len(_row.List))
		for j, _row2 := range _row.List {

			// 解析detail数据
			_list[j] = l._parseDetail(_typeSlice, _nameSlice, _row2)
		}

		sort.Slice(_list, func(i, j int) bool {
			return _list[i].Tier < _list[j].Tier
		})
		_data[i] = types.RebatesFeeRateInfo{
			Level: _row.Level,
			List:  _list,
		}
	}

	sort.Slice(_data, func(i, j int) bool {
		return _data[i].Level < _data[j].Level
	})

	resp = &types.RebatesFeeRateList{
		List: _data,
	}

	return
}

func (l *GetRebatesFeeRateListLogic) _parseDetail(_typeSlice []string, _nameSlice []string, row *rpc.RebatesFeeRate) types.RebatesFeeRateForList {
	// 解析detail数据
	_valueSlice := make([]float64, len(_typeSlice))

	for i, v := range _typeSlice {
		var found = false
		for _, _row3 := range row.Detail {
			if v == _row3.Type {
				_valueSlice[i] = _row3.FeeRate
				found = true
				break
			}
		}

		if !found {
			_valueSlice[i] = 0
		}
	}
	return types.RebatesFeeRateForList{
		Id:        row.ID,
		Level:     row.Level,
		Tier:      row.Tier,
		Type:      _typeSlice,
		Name:      _nameSlice,
		Value:     _valueSlice,
		CreatedAt: row.CreatedAt,
		UpdatedAt: row.UpdatedAt,
	}
}
